<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>AI 文生图工具</title>
    <style>
        :root {
            --primary-color: #1890ff;
            --error-color: #ff4d4f;
            --shadow-color: rgba(24,144,255,0.15);
            --border-radius: 12px;
        }

        body {
            max-width: 800px;
            margin: 20px auto;
            padding: 40px 30px;
            font-family: system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, #e6f7ff 0%, #f0ebff 100%);
            border-radius: 24px;
            box-shadow: 0 12px 40px var(--shadow-color);
        }

        .control-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        input[type="text"],
        input[type="number"],
        textarea {
            width: 100%;
            padding: 12px;
            margin-bottom: 15px;
            border: 2px solid #69c0ff;
            border-radius: var(--border-radius);
            background: rgba(255,255,255,0.95);
            box-shadow: 0 4px 16px var(--shadow-color);
            transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        button {
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
            transition: all 0.2s;
        }

        #generateBtn {
            background: linear-gradient(135deg, var(--primary-color), #096dd9);
            box-shadow: 0 4px 12px var(--shadow-color);
        }

        #downloadBtn {
            background: linear-gradient(135deg, #52c41a, #389e0d);
            display: none;
            margin-top: 15px;
        }

        button:not(:disabled):hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(24,144,255,0.4);
        }

        button:disabled {
            background: #d9d9d9;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #preview {
            margin-top: 20px;
            text-align: center;
        }

        #imageContainer {
            max-width: 100%;
            margin-top: 20px;
            border: 2px solid #bae7ff;
            padding: 20px;
            border-radius: 16px;
            background: rgba(255,255,255,0.95);
            box-shadow: 0 8px 32px rgba(24,144,255,0.1);
            transition: transform 0.3s ease;
        }

        #loading {
            display: none;
            color: var(--primary-color);
            text-align: center;
            padding: 15px;
            font-weight: bold;
        }

        .error {
            color: var(--error-color);
            padding: 10px;
            margin: 10px 0;
            border-radius: var(--border-radius);
            display: none;
        }
    </style>
</head>
<body>
    <h2>AI 图片生成器</h2>
    <div class="error" id="errorMsg"></div>

    <div class="control-group">
        <label for="prompt">提示词:</label>
        <textarea id="prompt" placeholder="请输入图片描述（至少5个字）" rows="4" required></textarea>
    </div>

    <div class="control-group">
        <label for="width">宽度 (100-2048):</label>
        <input type="number" id="width" value="1024" min="100" max="2048" required>
    </div>

    <div class="control-group">
        <label for="height">高度 (100-2048):</label>
        <input type="number" id="height" value="576" min="100" max="2048" required>
    </div>

    <div class="control-group">
        <label for="seed">随机种子:</label>
        <input type="number" id="seed" value="100" min="0" required>
    </div>

    <button id="generateBtn" onclick="generateImage()">生成图片</button>
    <div id="loading">图片生成中，请稍候...</div>

    <div id="preview">
        <h3>图片预览</h3>
        <div id="imageContainer">
            <img id="generatedImage" alt="生成的图片" style="max-width: 100%">
            <button id="downloadBtn">⬇ 下载图片</button>
        </div>
    </div>

    <script>
        async function generateImage() {
            const btn = document.getElementById('generateBtn');
            const loading = document.getElementById('loading');
            const errorMsg = document.getElementById('errorMsg');
            const downloadBtn = document.getElementById('downloadBtn');

            try {
                errorMsg.style.display = 'none';
                btn.disabled = true;
                loading.style.display = 'block';
                downloadBtn.style.display = 'none';

                const prompt = document.getElementById('prompt').value.trim();
                const widthInput = document.getElementById('width');
                const heightInput = document.getElementById('height');
                const seedInput = document.getElementById('seed');

                if (!prompt || prompt.length < 5) {
                    showError('提示词至少需要5个字符');
                    return;
                }

                const width = Math.min(Math.max(parseInt(widthInput.value), 100), 2048);
                const height = Math.min(Math.max(parseInt(heightInput.value), 100), 2048);
                let seed = parseInt(seedInput.value) || 0;

                widthInput.value = width;
                heightInput.value = height;
                seedInput.value = ++seed;

                const params = new URLSearchParams({
                    width: width,
                    height: height,
                    seed: seed,
                    model: 'flux',
                    nologo: true
                });

                const imageUrl = `https://image.pollinations.ai/prompt/${encodeURIComponent(prompt)}?${params}`;

                await loadImage(imageUrl);
                document.getElementById('generatedImage').src = imageUrl;
                downloadBtn.style.display = 'block';
                downloadBtn.onclick = () => downloadImage(imageUrl, prompt);

            } catch (error) {
                showError(`生成失败: ${error.message}`);
            } finally {
                btn.disabled = false;
                loading.style.display = 'none';
            }
        }

        async function downloadImage(url, prompt) {
            try {
                const response = await fetch(url);
                if (!response.ok) throw new Error('服务器响应异常');

                const blob = await response.blob();
                const filename = generateFileName(prompt);

                const link = document.createElement('a');
                const objectURL = URL.createObjectURL(blob);

                link.href = objectURL;
                link.download = filename;
                link.style.display = 'none';

                document.body.appendChild(link);
                link.click();

                // 清理资源
                setTimeout(() => {
                    document.body.removeChild(link);
                    URL.revokeObjectURL(objectURL);
                }, 100);

            } catch (error) {
                showError(`下载失败: ${error.message}`);
            }
        }

        function loadImage(url) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => resolve(img);
                img.onerror = () => reject(new Error('图片加载失败，请检查网络连接或提示词'));
                img.src = url;
            });
        }

        function generateFileName(prompt) {
            const cleanPrompt = prompt
                .substring(0, 30)
                .replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_')
                .replace(/_+/g, '_');
            return `AI_${cleanPrompt}_${Date.now()}.png`;
        }

        function showError(message) {
            const errorMsg = document.getElementById('errorMsg');
            errorMsg.textContent = message;
            errorMsg.style.display = 'block';
            setTimeout(() => errorMsg.style.display = 'none', 3000);
        }
    </script>
</body>
</html>